package chapter6.section3;

//程序6-3：Account类覆盖了超类的equals方法和hashCode方法
public class Account {
	private String id;// 账户id，唯一性的标识
	private String name;// 账户拥有人的姓名
	private int balance;// 余额

	public Account(String id, String name, int balance) {
		this.id = id;
		this.name = name;
		this.balance = balance;
	}

	// 取款的方法,返回本次取出的金额，如果为0，表示余额不足
	public int withdraw(int amount) {
		int result = 0;
		if (this.balance >= amount) {
			this.balance = this.balance - amount;
			result = amount;
		}
		return result;
	}

	public int getBalance() {
		return this.balance;
	}

	public void setBalance(int balance) {
		this.balance = balance;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)// 如果两个变量引用的是一个对象，则相等
			return true;
		if (obj == null)// 如果比较对象不存在，则不相等
			return false;
		if (!(obj instanceof Account))// 如果比较对象类型不匹配，则不相等
			return false;
		final Account other = (Account) obj;// 转换比较对象类型为Account
		if (id == null) {// 如果当前对象id尚未赋值，而比较对象id已赋值，则不相等
			if (other.getId() != null)
				return false;
		} else if (!id.equals(other.getId()))// 如果两个对象的id不等，则不相等
			return false;
		return true;// 排除以上不相等的情况，两个对象逻辑上是相等的
	}

	public static void main(String[] args) {
		Account a1 = new Account("001", "鲁宁", 1000);
		Account a2 = new Account("001", "鲁宁", 1000);
		boolean result = (a1 == a2);
		System.out.println("a1==a2 =" + result);
		result = a1.equals(a2);
		System.out.println("a1.equals(a2)=" + result);
	} 
}
